aboutsummaryrefslogtreecommitdiff
path: root/src/routes/grocery/[id]/+page.server.ts
blob: 88aa1377b8fb179666f01b4a11586215d3e15d65 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71

import { error, fail, redirect } from '@sveltejs/kit';
import { db } from '$lib/server/db';
import { groceries, categories, references } from '$lib/server/db/schema';
import { eq } from 'drizzle-orm';
import type { Actions, PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ params }) => {
	const id = Number(params.id);

	const [item] = await db.select().from(groceries).where(eq(groceries.id, id));
	if (!item) throw error(404, 'Item not found');

	const [cat] = item.categoryId
		? await db
				.select()
				.from(categories)
				.where(eq(categories.id, item.categoryId))
		: [null];

	const refs = await db
		.select()
		.from(references)
		.where(eq(references.groceryId, id));

	return {
		item: {
			...item,
			categoryName: cat?.name ?? null,
		},
		references: refs,
	};
};

export const actions: Actions = {
	add: async ({ request, params }) => {
		const data = await request.formData();
		const brand = data.get('brand')?.toString().trim();
		const price = data.get('price')?.toString().trim();
		const unit = data.get('unit')?.toString().trim();
		const qualityScore = data.get('quality_score')?.toString().trim();

		if (!brand) {
			return fail(400, { error: 'Brand is required' });
		}

		await db.insert(references).values({
			groceryId: Number(params.id),
			brand,
			price: price ? Number(price) : null,
			unit: unit || null,
			qualityScore: qualityScore ? Number(qualityScore) : null,
		});

		return { success: true };
	},

	delete: async ({ request }) => {
		const data = await request.formData();
		const id = Number(data.get('id'));

		await db.delete(references).where(eq(references.id, id));

		return { success: true };
	},

	deleteItem: async ({ params }) => {
		await db.delete(groceries).where(eq(groceries.id, Number(params.id)));

		throw redirect(303, '/');
	},
};